package cn.hy.preparelesson.common.service;

import cn.hy.pms.thrift.SysUserThrift;
import cn.hy.pms.thrift.utils.ThriftUtils;
import cn.hy.preparelesson.common.entity.PlComment;
import cn.hy.preparelesson.common.entity.PlCommentExample;
import cn.hy.preparelesson.common.entity.PlLesson;
import cn.hy.preparelesson.common.enums.DataStatus;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.mapper.PlCommentMapper;
import cn.hy.preparelesson.common.params.PageParams;
import cn.hy.preparelesson.common.utils.IdUtils;
import cn.hy.preparelesson.common.vo.PageInfo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 备课评论Service
 */

@Service
public class PlCommentService extends  BaseService {

    @Autowired
    private PlCommentMapper plCommentMapper ;

    @Autowired
    private PlLessonService plLessonService;
    /**
     * 查询 评论 - 备课 list
     * @param schoolId
     * @param lessonId
     * @return
     */
    public List<PlComment> findValidPlCommentListBySchoolIdAndLessonId(String schoolId, String lessonId) {
        PlCommentExample example = new PlCommentExample();
        example.createCriteria().andStatusEqualTo(DataStatus.NORMAL.getCode()).andSchoolIdEqualTo(schoolId).andLessonIdEqualTo(lessonId);
        example.setOrderByClause("update_at desc");
       return   plCommentMapper.selectByExample(example);
    }

    /**
     * 根据schoolId lessonIdList 查询 评论-备课集合
     * @param schoolId
     * @param lessonIdList
     * @return
     */
    public List<PlComment> findValidListBySchoolIdAndLessonIdIn(String schoolId, List<String> lessonIdList){
        PlCommentExample example = new PlCommentExample() ;
        example.createCriteria().andSchoolIdEqualTo(schoolId)
                .andStatusEqualTo(DataStatus.NORMAL.getCode())
                .andLessonIdIn(lessonIdList);
     return plCommentMapper.selectByExample(example);
    }

    /**
     * 获取评论
     * @param id
     * @param schoolId
     * @param createBy
     * @return
     */
    public PlComment findValidPlCommentBy(String id, String schoolId, String createBy) {
        PlCommentExample example = new PlCommentExample();
        PlCommentExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(DataStatus.NORMAL.getCode()).andIdEqualTo(id).andSchoolIdEqualTo(schoolId);
        if (StringUtils.isNotBlank(createBy)) {
            criteria.andCreateByEqualTo(createBy);
        }
        List<PlComment> plComments = plCommentMapper.selectByExample(example);
        return CollectionUtils.isEmpty(plComments) ? null : plComments.get(0);
    }

    /**
     * 分页 获取 备课-评论 数据
     * @param schoolId
     * @param pageParams
     * @param lessonId
     * @return
     */
    public PageInfo<PlComment>  findValidPageBy(String schoolId, PageParams pageParams, String lessonId) throws TException {
        PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());

        PlCommentExample example = new PlCommentExample();
        example.createCriteria().andStatusEqualTo(DataStatus.NORMAL.getCode()).andSchoolIdEqualTo(schoolId).andLessonIdEqualTo(lessonId);
        example.setOrderByClause("update_at desc");

        List<PlComment> plCommentList =  plCommentMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(plCommentList)) {
            return new PageInfo<>();
        }
        PageInfo<PlComment> commentPageInfo = new PageInfo<>(plCommentList);
         buildPlCommentList(commentPageInfo.getList());

        return commentPageInfo;
    }

    /**
     * 保存评论信息
     * @param schoolId
     * @param opeUserId
     * @param plComment
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(String schoolId, String opeUserId, PlComment plComment) {
        PlLesson checkPlLesson = plLessonService.findValidPlLessonBySchoolIdAndId(schoolId, plComment.getLessonId());
        if (checkPlLesson == null) {
            throw new MessageException("当前备课不存在或者已被删除!");
        }
        Date now = new Date();
        plComment.setId(IdUtils.newId());
        plComment.setCreateAt(now);
        plComment.setCreateBy(opeUserId);
        plComment.setUpdateAt(now);
        plComment.setUpdateBy(opeUserId);
        plComment.setSchoolId(schoolId);
        plComment.setStatus(DataStatus.NORMAL.getCode());
        plCommentMapper.insert(plComment);
    }

    /**
     * 修改备课-评论
     * @param schoolId
     * @param opeUserId
     * @param plComment
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(String schoolId, String opeUserId, PlComment plComment) {
        PlComment curPlComment = findValidPlCommentBy(plComment.getId(), schoolId, opeUserId);
        if (curPlComment == null) {
            throw new MessageException("当前评论不存在！");
        }
        PlLesson checkPlLesson = plLessonService.findValidPlLessonBySchoolIdAndId(schoolId, plComment.getLessonId());
        if (checkPlLesson == null) {
            throw new MessageException("当前备课不存在！");
        }
        curPlComment.setUpdateAt(new Date());
        curPlComment.setContent(plComment.getContent());
        curPlComment.setUpdateBy(opeUserId);
        plCommentMapper.updateByPrimaryKey(curPlComment);
    }

    /**
     * 根据 id 软删除 评论
     * @param schoolId
     * @param opeUserId
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void softDeleteById(String schoolId, String opeUserId, String id) {
        PlComment curPlComment = findValidPlCommentBy(id, schoolId, opeUserId);
        if (curPlComment == null) {
            throw new MessageException("当前评论不存在！");
        }
        PlComment plCommentForUpDate = new PlComment();
        plCommentForUpDate.setId(id);
        plCommentForUpDate.setUpdateBy(opeUserId);
        plCommentForUpDate.setUpdateAt(new Date());
        plCommentForUpDate.setStatus(DataStatus.DELETE.getCode());
        plCommentMapper.updateByPrimaryKeySelective(plCommentForUpDate);
    }


    /**
     * 构建评论列表
     * @param commentList
     * @return
     */
    public void buildPlCommentList(List<PlComment> commentList) throws TException {
        if (CollectionUtils.isEmpty(commentList)) {
            return  ;
        }
        List<String> userIdList = commentList.stream().map(PlComment::getCreateBy).collect(Collectors.toList());
        List<SysUserThrift> sysUserList = ThriftUtils.findUserByUserIdList(userIdList);
        if (CollectionUtils.isEmpty(sysUserList)) {
            return ;
        }
//        List<PlComment> resCommentList = new ArrayList<>();
        for(PlComment plComment : commentList) {
            SysUserThrift curSysUser = sysUserList.stream().filter(sysUser -> sysUser.getId().equals(plComment.getCreateBy())).findFirst().orElse(null);
            if (curSysUser != null) {
                plComment.setCreateName(curSysUser.getRealName());
//                resCommentList.add(plComment);
            }
        }
    }
}
